#!/usr/bin/env node
import * as fs from "fs";
export class watchfile {
    private static _instance: watchfile = null;
    public static get instance() {
        if (!this._instance) {
            this._instance = new watchfile();
        }
        return this._instance;
    }
    private index: number = 0;
    private callbackobj: ({
        [index: number]: {
            callback?: Function,
            thisobj?: any,
            fsobj?: watchobj[]
        }
    }) = {};

    watchchange(path: string, callback: (type: string, filename: string) => void, thisobj: any) {
        this.index++;
        let call = (path1: string) => {
            let tt = new watchobj(path1, this.index, this.getfilechange, this);
            this.callbackobj[this.index].fsobj.push(tt);
        }
        if(!this.callbackobj[this.index]){
            this.callbackobj[this.index] = {
                callback: callback,
                thisobj: thisobj,
                fsobj: []
            }
        };
        let call1 = (path2: string)=>{
            call(path2)
            if(!fs.statSync(path2).isFile()){
                let list = fs.readdirSync(path2);
                list.forEach((element, index)=>{
                    let str = path2+"/"+element;
                    str = str.replace(/\\+/g, "/");
                    call1(str);
                },this)
            }
        };
        call1(path);
        return this.index;
    }

    public getfilechange(type: string, filename: string, index: number) {

    }


    off(index: number){
        if(this.callbackobj[index] && this.callbackobj[index].fsobj){
            for(let i = 0; i < this.callbackobj[index].fsobj.length; i++){
                let data = this.callbackobj[index].fsobj[i];
                data.fswatch.removeAllListeners();
            }
        }
        delete this.callbackobj[index];
    }
}

export class watchobj {
    public type: number;
    public path: string;
    public callback: (type: string, filename: string, index: number) => void;
    public thisobj: any;
    public fswatch: fs.FSWatcher;
    constructor(path: string,index: number, callback: (type: string, filename: string, index: number) => void, thisobj: any) {
        this.path = path;
        this.type = index;
        this.callback = callback;
        this.thisobj = thisobj;
        this.fswatch = fs.watch(path, (type1, filename) => {
            if(this.callback){
                this.callback.call(this.thisobj,type1,this.path,this.type);
            }
        })
        return this;
    }
}

// console.log(watchfile.instance.show())